package cn.yunyichina.provider.base.service.impl;

import cn.yunyichina.provider.base.dao.*;
import cn.yunyichina.provider.base.entity.*;
import cn.yunyichina.provider.base.vo.*;
import cn.yunyichina.provider.framework.annotation.validate.ValidateException;
import cn.yunyichina.provider.framework.annotation.validate.Validator;
import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.framework.dubbo.service.BoneService;
import cn.yunyichina.provider.framework.dubbo.service.FinanceService;
import cn.yunyichina.provider.framework.dubbo.service.MessageService;
import cn.yunyichina.provider.iface.entity.common.ResCommon;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.common.ResponseObject;
import cn.yunyichina.provider.iface.entity.finance.AccountJournalVo;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import cn.yunyichina.utils.security.MD5Util;
import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zd on 2017/4/24.
 */
@Service("orguserServiceImpl")
public class OrgUserServiceImpl {
    private static final Logger logger = LoggerFactory.getLogger(OrgUserServiceImpl.class);
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Autowired
    private OrgUserDao orgUserDao;
    @Autowired
    private DeptUserRelationDao deptUserRelationDao;
    @Autowired
    private OrgUserAttributeRelationDao orgUserAttributeRelationDao;
    @Autowired
    private OrgUserAttributeDao orgUserAttributeDao;
    @Autowired
    private DictionaryDao dictionaryDao;
    /**
     * 新增专家，新增主治医生(骨科)
     * @param data
     * @interfaceName: yyt.base.orguser.add
     * @return
     */
    public ResponseObject addOrgUser(String data){
        logger.info("OrgUserServiceImpl.addOrgUser 新增医生 json:" + JsonUtils.toJsonString(data));
        ResponseObject response = new ResponseObject();
        AddUserRequestVo requestVo = JsonUtils.parseObject(data,AddUserRequestVo.class);
        //检查参数合法性
        try {
            Validator.getInstance().validate(requestVo);
        } catch (ValidateException ex) {
            logger.info(" 数据校验失败:" + ex.getMessage() + "|入参:" + data + "！");
            logger.error("error", ex);
            response.setResultCodeAndMessage("1001", "数据校验失败:" + ex.getMessage() + "！");
            return response;
        }
        try{
            logger.info("新增医生信息开始");
            OrgUser orgUser = new OrgUser();
            try {
                OrgUser queryOrgUser = new OrgUser();
                queryOrgUser.setLoginName(requestVo.getMobile());
                List<OrgUser> orgUserList = orgUserDao.select(queryOrgUser);
                if (CollectionUtils.isNotEmpty(orgUserList)){
                    response.setResultCodeAndMessage("1001", "手机号码已经被占用,无需再次注册");
                    return response;
                }

                orgUser.setId(PKGenerator.generateId());
                orgUser.setUserName(requestVo.getUserName());
                orgUser.setMobile(requestVo.getMobile());
                if(org.apache.commons.lang.StringUtils.isBlank(requestVo.getSalt())){
                    orgUser.setSalt("123456");
                    String checkPassword= MD5Util.string2MD5(MD5Util.string2MD5("123456") + orgUser.getSalt());
                    orgUser.setPassword(checkPassword);
                }else{
                    orgUser.setSalt(requestVo.getSalt());
                    String checkPassword= MD5Util.string2MD5(MD5Util.string2MD5("123456") + requestVo.getSalt());
                    orgUser.setPassword(checkPassword);
                }
                orgUser.setLoginName(requestVo.getMobile());
                orgUser.setEmail(requestVo.getEmail());
                orgUser.setAddress(requestVo.getAddress());
                orgUser.setDescription(requestVo.getDescription());
                orgUser.setSkill(requestVo.getSkill());
                orgUser.setHeadImg(requestVo.getHeadImg());
                orgUser.setIdCardImg(requestVo.getIdCardImg());
                orgUser.setUserType(requestVo.getUserType());
                orgUser.setShowOrders(requestVo.getShowOrders());
                orgUser.setExtraParams(requestVo.getExtraParams());
                orgUser.setCreatedTime(DateUtils.getDateTimeStr());
                if(requestVo.getEnableFlag() != null){
                    orgUser.setEnableFlag(requestVo.getEnableFlag());
                }else{
                    orgUser.setEnableFlag(new Short("1"));
                }
                orgUser.setChannelType(requestVo.getChannelType());
                //二期新增推荐人信息
                orgUser.setIntroducerId(requestVo.getIntroducerId());
                orgUser.setIntroducerName(requestVo.getIntroducerName());
                if(org.apache.commons.lang.StringUtils.isNotBlank(requestVo.getIntroducerBonus())){
                    orgUser.setIntroducerBonus(Integer.valueOf(requestVo.getIntroducerBonus()));

                    //把推荐人奖金计算到医生费用中
                    AccountJournalVo accountJournalVo = new AccountJournalVo();
                    accountJournalVo.setId(PKGenerator.generateId());
                    accountJournalVo.setOrgId(requestVo.getOrgId());
                    accountJournalVo.setOrgName(requestVo.getOrgName());
                    accountJournalVo.setDeptId(requestVo.getDeptId());
                    accountJournalVo.setDeptName(requestVo.getDeptName());
                    accountJournalVo.setUserId(orgUser.getIntroducerId());
                    accountJournalVo.setUserName(orgUser.getIntroducerName());
                    accountJournalVo.setBusinessType((short) 15);
                    accountJournalVo.setBusinessDesc("奖励金收入");
                    accountJournalVo.setAmountDirection((short)  1);
                    accountJournalVo.setAmount(orgUser.getIntroducerBonus());
                    accountJournalVo.setCreatedTime(DateUtils.getDateTimeStr());
                    accountJournalVo.setIntroducerId(orgUser.getId());
                    accountJournalVo.setIntroducerName(orgUser.getUserName());

                    FinanceService.getFinanceClient().addAccountJournal(accountJournalVo);
                }

                if(requestVo.getLable() !=null){
                    logger.info("新增医生标签开始");
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("lable_id",requestVo.getLable());
                    jsonObject.put("doctor_id",orgUser.getId());
                    logger.info("新增医生标签入参]" + JsonUtils.toJsonString(jsonObject));
                    Response messageRep = BoneService.callHumpFromInternal("yyt.bone.doctor.lable.save", JsonUtils.toJsonString(jsonObject));
                    logger.info("新增医生标签出参 " + JsonUtils.toJsonString(messageRep));
                    if(!"0".equals(messageRep.getResultCode())){
                        response.setResultCodeAndMessage("-1","新增标签出错");
                        return response;
                    }
                    logger.info("更新医生标签结束");
                }
                orgUserDao.insert(orgUser);
                logger.info("新增医生信息结束");
            }catch (Exception e){
                logger.error("新增医生信息出错",e);
                response.setResultCodeAndMessage("-1","新增医生信息出错");
                return response;
            }

            logger.info("新增医生跟科室关系表开始");
            DeptUserRelation deptUserRelation = new DeptUserRelation();
            deptUserRelation.setId(PKGenerator.generateId());
            deptUserRelation.setDeptId(requestVo.getDeptId());
            deptUserRelation.setDeptName(requestVo.getDeptName());
            deptUserRelation.setOrgId(requestVo.getOrgId());
            deptUserRelation.setOrgName(requestVo.getOrgName());
            deptUserRelation.setUserId(orgUser.getId());
            deptUserRelation.setUserName(orgUser.getUserName());
            deptUserRelation.setUserStatus(new Short("1"));
            deptUserRelation.setEnableFlag(new Short("1"));
            deptUserRelation.setDefaultFlag((short) 1);
            deptUserRelation.setLastLoginTime(DateUtils.getDateTimeStr());
            deptUserRelationDao.insert(deptUserRelation);
            logger.info("新增医生跟科室关系表结束 准备执行短信推送");

            //调用短信
            Map<String, String> smsMap = new HashMap<>();
            smsMap.put("doctorName", requestVo.getUserName());
            smsMap.put("mobile", requestVo.getMobile());
            smsMap.put("platformType", requestVo.getPlatformType());

            ResponseObject smsReps = sendSms(smsMap);

            if("0".equals(smsReps.getResultCode())){
                logger.info("新增医生短信发送成功！");
            }else{
                logger.info("新增医生短信发送失败,失败原因：" + smsReps.getResultMessage());
            }

            response.setResultCodeAndMessage("0","成功");
            return response;
        }catch (Exception e){
            logger.error("新增医生信息出错",e);
            response.setResultCodeAndMessage("-1","新增医生信息出错");
            return response;
        }

    }

    private OrgUserAttributeRelation buildOrgUserAttributeRelation(OrgUser orgUser,JSONObject attributeObject,String attributeName){

        OrgUserAttributeRelation attributeRelation = new OrgUserAttributeRelation();
        List<OrgUserAttribute>  userAttributes = orgUserAttributeDao.selectByAttributeName(attributeName);
        attributeRelation.setId(PKGenerator.generateId());
        attributeRelation.setUserId(orgUser.getId());
        attributeRelation.setUserName(orgUser.getUserName());
        attributeRelation.setAttributeId(userAttributes.get(0).getId());
        attributeRelation.setAttributeName(userAttributes.get(0).getAttributeName());
        attributeRelation.setAttributeDesc(userAttributes.get(0).getAttributeDesc());
        attributeRelation.setInputType(userAttributes.get(0).getInputType());
        attributeRelation.setAttributeProperties(attributeObject.getString(attributeName));

        return attributeRelation;
    }


    /**
     * 推荐同仁信息
     * @param data
     * @interfaceName: yyt.base.orguser.and.dept.get
     * @return
     */
    public ResponseObject getOrgUserAndDept(String data){
        ResponseObject response = new ResponseObject();
        logger.info("[OrgUserServiceImpl.getOrgUserAndDept]  入参信息：" + JSONObject.toJSONString(data));

        OrgUser orgUser = JsonUtils.parseObject(data, OrgUser.class);
        if(orgUser != null){
            List<Map<String, Object>> maps = orgUserDao.getOrgUserAndDeptUser(orgUser.getIntroducerId() , orgUser.getEnableFlag());
            response.setResultCodeAndMessageAndResult(Response.SUCCESS_CODE , Response.SUCCESS_MESSAGE , JsonUtils.toJsonString(maps));
        }else{
            response.setResultCodeAndMessage(Response.FAILURE_CODE , "查无结果");
        }

        return response;
    }


    /**
     * 查询医生列表
     * @param data
     * @interfaceName: yyt.base.orguser.list
     * @return
     */
    public ResponseObject listOrgUser(String data){
        ResponseObject responseObject = new ResponseObject();
        try {
            logger.info("OrgUserServiceImpl->listOrgUser request data ={}",data);
            Map<String,Object> resultMap = new HashMap<String,Object>();
            ListOrgUserRequestVo request = JsonUtils.parseObject(data,ListOrgUserRequestVo.class);
            Map<String, Object> params = new HashMap<String ,Object>();
            if (request.getUserType() !=null){
                params.put("userType",request.getUserType());
            }
            if (request.getDoctorName() !=null){
                params.put("userName",request.getDoctorName());
            }
            if (request.getOrgId() !=null){
                params.put("orgId",request.getOrgId());
            }
            if (request.getDeptId() !=null){
                params.put("deptId",request.getDeptId());
            }
            if (request.getMobile() !=null){
                params.put("mobile",request.getMobile());
            }
            if (StringUtils.isNotEmpty(request.getUserIds())){
                String[] userIds = request.getUserIds().split(",");
                params.put("userIds",userIds);
            }

            if (request.getPageNum() !=null){
                params.put("pageNum",request.getPageNum());
            }
            if (request.getPageSize() !=null){
                params.put("pageSize",request.getPageSize());
            }
            if (request.getOrgType() !=null){
                params.put("coopOrgType",request.getOrgType());
            }
            if (request.getCoopCityId() !=null){
                params.put("coopCityId",request.getCoopCityId());
            }
            if (request.getEnableFlag() !=null){
                params.put("enableFlag",request.getEnableFlag());
            }

            if (request.getChannelType() !=null){
                params.put("channelType",request.getChannelType());
            }

            if(request.getExtraParams() != null){
                params.put("extraParams",request.getExtraParams());
            }
            if(request.getLable() !=null){
                params.put("lable",request.getLable());
            }

            List<OrgUserVo>datas = orgUserDao.getOrgUser(params);
            resultMap.put("datas",datas);
            long datasCount = orgUserDao.selectOrgUserCount(params);
            resultMap.put("datasCount", String.valueOf(datasCount));
            logger.info("OrgUserServiceImpl->listOrgUser response data ={}",JSON.toJSONString(resultMap));
            responseObject.setResultCodeAndMessageAndResult("0","成功",resultMap);
        }catch (Exception e){
            logger.error("查询医生列表信息出错",e);
            responseObject.setResultCodeAndMessage("-1","查询医生信息失败");
        }

        return responseObject;
    }


    /**
     * 修改专家，新增主治医生
     * @param data
     * @interfaceName: yyt.base.orguser.update
     * @return
     */
    @Transactional
    public ResponseObject updateOrgUser(String data){
        logger.info("OrgUserServiceImpl.updateOrgUser 修改医生 json:" + JsonUtils.toJsonString(data));
        ResponseObject responseObject = new ResponseObject();
        try {
            UpdateOrgUserVoRequest requestVo = JsonUtils.parseObject(data,UpdateOrgUserVoRequest.class);

            OrgUser dbOrgUser = orgUserDao.selectById(requestVo.getUserId());

            if (dbOrgUser==null){
                responseObject.setResultCodeAndMessage("-1","不存在该医生");
                return responseObject;
            }

            if (requestVo.getUserType() !=null){
                OrgUser queryOrgUser = new OrgUser();
                queryOrgUser.setLoginName(requestVo.getMobile());
                List<OrgUser> orgUserList = orgUserDao.select(queryOrgUser);
                if (CollectionUtils.isNotEmpty(orgUserList)){
                    if (!dbOrgUser.getId().equals(orgUserList.get(0).getId())){
                        responseObject.setResultCodeAndMessage("1001","手机号码已经被占用");
                        return responseObject;
                    }
                }
            }

            logger.info("更新医生基本信息表开始");
            Integer dbUserType = dbOrgUser.getUserType();

            dbOrgUser.setUserName(requestVo.getUserName());
            dbOrgUser.setEmail(requestVo.getEmail());
            dbOrgUser.setAddress(requestVo.getAddress());
            dbOrgUser.setMobile(requestVo.getMobile());
            dbOrgUser.setLoginName(requestVo.getMobile());
            dbOrgUser.setUserType(requestVo.getUserType());
            dbOrgUser.setHeadImg(requestVo.getHeadImg());
            dbOrgUser.setIdCardImg(requestVo.getIdCardImg());
            dbOrgUser.setShowOrders(requestVo.getShowOrders());
            dbOrgUser.setDescription(requestVo.getDescription());
            dbOrgUser.setExtraParams(requestVo.getExtraParams());
            dbOrgUser.setIntroducerId(requestVo.getIntroducerId());
            dbOrgUser.setIntroducerName(requestVo.getIntroducerName());
            dbOrgUser.setSkill(requestVo.getSkill());
            if(requestVo.getEnableFlag() != null){
                dbOrgUser.setEnableFlag(requestVo.getEnableFlag());
            }
            if(requestVo.getChannelType() != null){
                dbOrgUser.setChannelType(requestVo.getChannelType());
            }
            if(org.apache.commons.lang.StringUtils.isNotBlank(requestVo.getIntroducerBonus())){
                dbOrgUser.setIntroducerBonus(Integer.valueOf(requestVo.getIntroducerBonus()));

                if(StringUtils.isBlank(requestVo.getOrgId()) || StringUtils.isBlank(requestVo.getDeptId()) || StringUtils.isBlank(requestVo.getUserId())){
                    responseObject.setResultCodeAndMessage("-1","无法修改奖励金金额。请检查传入orgId , deptId , userId 是否为空值");
                    return responseObject;
                }
                AccountJournalVo accountJournalVo = new AccountJournalVo();
                accountJournalVo.setOrgId(requestVo.getOrgId());
                accountJournalVo.setDeptId(requestVo.getDeptId());
                accountJournalVo.setUserId(requestVo.getIntroducerId());
                accountJournalVo.setIntroducerId(requestVo.getUserId());
                accountJournalVo.setBusinessType((short) 15);

                //同时修改流水数据
                logger.info("OrgUserServiceImpl.updateOrgUser.selectAccountJournal 修改流水 json:" + JsonUtils.toJsonString(accountJournalVo));
                ResCommon<AccountJournalVo> resCommon = FinanceService.getFinanceClient().selectAccountJournal(JsonUtils.toJsonString(accountJournalVo));
                if("0".equals(resCommon.getResultCode())){
                    AccountJournalVo accountJournal = resCommon.getResult();
                    accountJournal.setAmount(Integer.valueOf(requestVo.getIntroducerBonus()));
                    FinanceService.getFinanceClient().updateAccountJournal(accountJournal);
                }else{
                    logger.info("不存在奖励金对应流水数据selectAccountJournal! json:" + JsonUtils.toJsonString(accountJournalVo) +" , resultMessage：" + resCommon.getResultMessage());
                    //如果不存在奖励金需新增一条，推荐人奖金计算到医生费用中
                    accountJournalVo = new AccountJournalVo();
                    accountJournalVo.setId(PKGenerator.generateId());
                    accountJournalVo.setOrgId(requestVo.getOrgId());
                    accountJournalVo.setOrgName(requestVo.getOrgName());
                    accountJournalVo.setDeptId(requestVo.getDeptId());
                    accountJournalVo.setDeptName(requestVo.getDeptName());
                    accountJournalVo.setUserId(requestVo.getIntroducerId());
                    accountJournalVo.setUserName(requestVo.getIntroducerName());
                    accountJournalVo.setBusinessType((short) 15);
                    accountJournalVo.setBusinessDesc("奖励金收入");
                    accountJournalVo.setAmountDirection((short)  1);
                    accountJournalVo.setAmount(Integer.valueOf(requestVo.getIntroducerBonus()));
                    accountJournalVo.setCreatedTime(DateUtils.getDateTimeStr());
                    accountJournalVo.setIntroducerId(dbOrgUser.getId());
                    accountJournalVo.setIntroducerName(dbOrgUser.getUserName());

                    FinanceService.getFinanceClient().addAccountJournal(accountJournalVo);
                }
            }
            orgUserDao.update(dbOrgUser);
            logger.info("更新医生基本信息表结束");

            logger.info("更新医生所属科室开始");
            /*查询出默认医生*/
            DeptUserRelation deptUser = new DeptUserRelation();
            deptUser.setUserId(requestVo.getUserId());
            deptUser.setEnableFlag((short) 1);
            List<DeptUserRelation> deptUserRelations = deptUserRelationDao.select(deptUser);

            for (DeptUserRelation userRelation : deptUserRelations) {
                if(userRelation.getDefaultFlag() == 1){
                    deptUser = userRelation;
                    logger.info("[updateOrgUser 获取到可用医生 id]" + deptUser.getId() +" , 名称：" + deptUser.getUserName());
                    break;
                }
            }

            if (deptUser ==null){
                responseObject.setResultCodeAndMessage("-1","该医生没有关联的科室信息");
                return responseObject;
            }
            deptUser.setOrgName(requestVo.getOrgName());
            deptUser.setOrgId(requestVo.getOrgId());
            deptUser.setUserName(requestVo.getUserName());
            deptUser.setDeptName(requestVo.getDeptName());
            deptUser.setDeptId(requestVo.getDeptId());
            deptUserRelationDao.update(deptUser);
            logger.info("更新医生所属科室结束");

            if(requestVo.getLable() !=null){
                logger.info("更新医生标签开始");
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("doctor_id",dbOrgUser.getId());
                jsonObject.put("lable_id",requestVo.getLable());
                logger.info("更新医生标签入参]" + JsonUtils.toJsonString(jsonObject));
                Response messageRep = BoneService.callHumpFromInternal("yyt.bone.doctor.lable.save", JsonUtils.toJsonString(jsonObject));
                logger.info("更新医生标签出参 " + JsonUtils.toJsonString(messageRep));
                if(!"0".equals(messageRep.getResultCode())){
                    responseObject.setResultCodeAndMessage("-1","更新医生标签出错");
                    return responseObject;
                }
                logger.info("更新医生标签结束");
            }


        }catch (Exception e){
            logger.info("修改医生信息出错",e);
            responseObject.setResultCodeAndMessage("-1","修改医生信息出错");
        }
        return responseObject;
    }

    public ResponseObject getOrgUserAttributes(String data){
        ResponseObject responseObject = new ResponseObject();
        try {
            logger.info("查询医生属性列表");
            ListOrgUserAttributeRequest request = JsonUtils.parseObject(data,ListOrgUserAttributeRequest.class);
            Dictionary dictionary = new Dictionary();
            dictionary.setDicCode(request.getAttributeName());
            List<Dictionary>  dictionarys = dictionaryDao.select(dictionary);
            responseObject.setResultCodeAndMessageAndResult("0","成功",dictionarys);
        }catch (Exception e){
            logger.error("查询医生属性列表出错",e);
            responseObject.setResultCodeAndMessage("-1","查询医生属性列表出错");
        }
        return  responseObject;
    }

    /**
     * 根据手机号码获取医生信息
     * @param data
     * @return
     */
    public ResponseObject getOrgUserByMobile(String data){
        ResponseObject responseObject = new ResponseObject();
        try {
            logger.info("根据手机号获取医生信息");
            Map<String ,String > request = JsonUtils.parseObject(data,Map.class);
            OrgUser orgUser = new OrgUser();
            orgUser.setLoginName(request.get("mobile"));
            if(StringUtils.isNotEmpty(request.get("enable_flag"))){
                orgUser.setEnableFlag(Short.valueOf(request.get("enable_flag")));
            }
            List<OrgUser> orgUserList = orgUserDao.select(orgUser);
            if (CollectionUtils.isEmpty(orgUserList)){
                responseObject.setResultCodeAndMessage("-1","查询医生不存在");
                return  responseObject;
            }
            responseObject.setResultCodeAndMessageAndResult("0","成功",orgUserList.get(0));
        }catch (Exception e){
            logger.error("查询医生出错",e);
            responseObject.setResultCodeAndMessage("-1","查询医生出错");
        }
        return  responseObject;
    }


    /**
     * 根据条件获取系统用户信息
     * @param data
     * @interfaceName: yyt.base.orguser.get
     * @return
     */
    public ResponseObject getOrgUser(String data){
        ResponseObject responseObject = new ResponseObject();
        try {
            logger.info("根据条件获取系统用户信息 json -->" + JSONUtils.toJSONString(data));
            OrgUser orgUser = JsonUtils.parseObject(data,OrgUser.class);
            List<OrgUser> orgUserList = orgUserDao.select(orgUser);
            if (CollectionUtils.isEmpty(orgUserList)){
                responseObject.setResultCodeAndMessage("-1","查询医生不存在");
                return  responseObject;
            }
            responseObject.setResultCodeAndMessageAndResult("0","成功",JsonUtils.toJsonString(orgUserList));
        }catch (Exception e){
            logger.error("查询医生出错",e);
            responseObject.setResultCodeAndMessage("-1","查询医生出错");
        }
        return  responseObject;
    }




    /**
     * 返回推荐人信息
     * @param data
     * @interfaceName: yyt.base.orguser.introducer.message.get
     * @return
     */
    public ResponseObject getOrgUserIntroducerMessage(String data){
        ResponseObject responseObject = new ResponseObject();
        try {
            JSONObject request = JSONObject.parseObject(data);
            String userId = request.getString("user_id");
            OrgUser firstIntroducer = orgUserDao.selectById(userId);
            OrgUser secondIntroducer = null;
            if (firstIntroducer==null){
                responseObject.setResultCodeAndMessage("1002","查询不到该医生");
                return  responseObject;
            }

            IntroducerMessageResponseVo result =null;
            if (!StringUtils.isBlank(firstIntroducer.getIntroducerId())){
                secondIntroducer = orgUserDao.selectById(firstIntroducer.getIntroducerId());
                if (secondIntroducer!=null){
                    result = buildIntroducerMessageResponseVo(firstIntroducer,secondIntroducer);
                    responseObject.setResultCodeAndMessageAndResult("0","成功",result);
                }else {
                    result = buildIntroducerMessageResponseVo(firstIntroducer,null);
                    responseObject.setResultCodeAndMessageAndResult("0","成功",result);
                }

            }else{
                result = buildIntroducerMessageResponseVo(firstIntroducer,null);
                responseObject.setResultCodeAndMessageAndResult("0","成功",result);
            }

        }catch (Exception e){
            responseObject.setResultCodeAndMessage("-1","获取医生推荐人信息异常");
            logger.error("获取医生推荐人信息异常" , e);
            return  responseObject;
        }
        return responseObject;
    }

    private IntroducerMessageResponseVo buildIntroducerMessageResponseVo(OrgUser firstIntroducer ,OrgUser secondIntroducer ){
        IntroducerMessageResponseVo result = new IntroducerMessageResponseVo();
        DeptUserRelation firstDeptUserRelation = deptUserRelationDao.selectByUserId(firstIntroducer.getIntroducerId());
        DeptUserRelation deptUser = new DeptUserRelation();
        deptUser.setUserId(firstIntroducer.getId());
        deptUser.setEnableFlag((short) 1);
        List<DeptUserRelation> deptUserRelations = deptUserRelationDao.select(deptUser);    //一个医生在多家医院任职，获取默认开启的医院
        for (DeptUserRelation deptUserRelation : deptUserRelations) {
            if(deptUserRelation.getDefaultFlag() == 1){
                deptUser = deptUserRelation;
                break;
            }
        }
        result.setUserId(firstIntroducer.getId());
        result.setUserName(firstIntroducer.getUserName());
        result.setOrgId(deptUser.getOrgId());
        result.setOrgName(deptUser.getOrgName());
        result.setDeptId(deptUser.getDeptId());
        result.setDeptName(deptUser.getDeptName());
        /**一级推荐人*/

        if (firstDeptUserRelation !=null){
            result.setFirstOrgId(firstDeptUserRelation.getOrgId());
            result.setFirstOrgName(firstDeptUserRelation.getOrgName());
            result.setFirstDeptId(firstDeptUserRelation.getDeptId());
            result.setFirstDeptName(firstDeptUserRelation.getDeptName());
        }
        result.setFirstIntroducerId(firstIntroducer.getIntroducerId());
        result.setFirstIntroducerName(firstIntroducer.getIntroducerName());
        /**二级推荐人*/
        if(secondIntroducer !=null){
            DeptUserRelation secondDeptUserRelation = deptUserRelationDao.selectByUserId(secondIntroducer.getIntroducerId());
            if (secondDeptUserRelation !=null){
                result.setSecondOrgId(secondDeptUserRelation.getOrgId());
                result.setSecondOrgName(secondDeptUserRelation.getOrgName());
                result.setSecondDeptId(secondDeptUserRelation.getDeptId());
                result.setSecondDeptName(secondDeptUserRelation.getDeptName());
            }
            result.setSecondIntroducerId(secondIntroducer.getIntroducerId());
            result.setSecondIntroducerName(secondIntroducer.getIntroducerName());
        }
        logger.info("获取推荐人信息返回前端:",new Object[]{JsonUtils.toJsonString(result)});
        return result;

    }

    /**
     * 获取用户部门信息 yyt.base.orguser.relation.get
     *
     * @param data
     * @return
     */
    public Response getOrgUserRelation(String data) {
        logger.info("获取用户部门信息[yyt.base.orguser.relation.get]，入参 data: " + data);
        JSONObject requestVo = JSON.parseObject(data);
        DeptUserRelation deptUserRelation = deptUserRelationDao.selectByUserId(requestVo.getString("user_id"));
        if (deptUserRelation == null) {
            logger.error("该医生没有关联的科室信息");
            return new Response("-1", "该医生没有关联的科室信息");
        }

        Response response = new Response();
        String resultJson = JSON.toJSONString(deptUserRelation);
        logger.info("获取用户部门信息[yyt.base.orguser.relation.get]，查询结果 deptUserRelation: " + resultJson);
        response.setResult(resultJson);
        return response;
    }

    /**
     * 获取指定医生信息 yyt.base.orguser.info.get
     *
     * @param data
     * @return
     */
    public Response getOrgUserInfo(String data) {
        logger.info("获取指定医生信息[yyt.base.orguser.info.get]，入参 data: " + data);
        JSONObject requestVo = JSON.parseObject(data);
        OrgUserVo orgUserVo = orgUserDao.getOrgUserByUserId(requestVo.getString("user_id"));
        if (orgUserVo == null) {
            logger.error("获取指定医生信息失败");
            return new Response("-1", "获取指定医生信息失败");
        }

        Response response = new Response();
        String resultJson = JSON.toJSONString(orgUserVo);
        logger.info("获取指定医生信息[yyt.base.orguser.info.get]，查询结果 orgUserVo: " + resultJson);
        response.setResult(resultJson);
        return response;
    }


    /**
     * 根据条件修改机构用户信息
     * @param data
     * @interfaceName: yyt.base.orguser.for.param.update
     * @return
     */
    public Response updateOrgUserForParam(String data) {
        logger.info("根据条件修改信息[yyt.base.orguser.for.param.update]，入参 data: " + data);
        Response response = new Response();
        OrgUser orgUser = JsonUtils.parseObject(data,OrgUser.class);

        if(org.apache.commons.lang.StringUtils.isNotBlank(orgUser.getId())){
            try {
                orgUser.setUpdateTime(DateUtils.getDateTimeStr());
                orgUserDao.update(orgUser);
                response.setResultCodeAndMessage(Response.SUCCESS_CODE , Response.SUCCESS_MESSAGE);
            } catch (Exception e) {
                logger.error("[OrgUserServiceImpl.updateOrgUserForParam 根据条件修改机构用户信息失败]" ,e);
                response.setResultCodeAndMessage(Response.FAILURE_CODE , "根据条件修改机构用户信息失败");
            }
        }

        return response;
    }



    /**
     * 构建发送新增医生成功短信（骨科）
     * @param paramMap
     * @return
     */
    public static ResponseObject sendSms(Map<String ,String> paramMap) {
        try {
            Map<String, String> map = new HashMap<>();
            map.put("sms_type" , "95");
            map.put("sms_mobile" , paramMap.get("mobile"));
            map.put("doctor_name" , paramMap.get("doctorName"));
            map.put("password" , "123456");

            String platformType = paramMap.get("platformType");
            if("1".equals(platformType)){
                map.put("connect" , "推广人员");
            }else{
                map.put("connect" , "医生");
            }
            return MessageService.sendSms(JsonUtils.toJsonString(map));
        } catch (Exception e) {
            logger.error("发送短信失败",e);
        }
        return null;
    }
}
